package com.atsmart.app.activity;

import java.io.IOException;
import java.io.Serializable;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import com.atsmart.app.BizApp;
import com.atsmart.app.R;
import com.atsmart.app.adapter.ClientAdapter;
import com.atsmart.app.adapter.LoadingAdapter;
import com.atsmart.app.exception.BizException;
import com.atsmart.app.model.ClientInfo;
import com.atsmart.app.model.ClientListInfo;
import com.atsmart.app.model.CommonBody;
import com.atsmart.app.model.LocationPageinfo;
import com.atsmart.app.model.ResultInfo;

import com.atsmart.app.sql.ClientDisSqlHelper;
import com.atsmart.app.sql.ClientSqlHelper;
import com.atsmart.app.sql.NumberSqlHelper;
import com.atsmart.app.utils.DialogUtil;
import com.atsmart.app.utils.IntentUtil;
import com.atsmart.app.utils.PersistentKeyUtil;
import com.atsmart.app.utils.PrefsUtils;
import com.atsmart.app.utils.StringUtil;
import com.atsmart.app.webservice.ServiceAsynTask;
import com.atsmart.app.webservice.ServiceHelper;
import com.atsmart.app.webservice.ServiceHost;
import com.google.json.Gson;
import com.google.json.JsonParseException;
import com.google.json.annotations.SerializedName;
/**
 * TODO 客户Activity
 */
public class ClientListActivity extends BaseActivity implements LoadingAdapter.Delegate, LoadingAdapter.OnLoadingRowShowingHandler, OnClickListener {
	
	private static final String TAG = ClientListActivity.class.getName();
	
	private ListView listView;
	private ClientListInfo datasource;
	private ClientAdapter adapter;
	private static final int pageSize = 20;
	private boolean isNeedLoading = false;
	private int totalRow;
	private int pageIndex = 0;
	private EditText txtKeyword;
	private Button btnSearch;
	private String keyword;
	private Button btnMap;
	private Button btnRef;
	private Gson gson;
	/**
	 * 存储客户信息SQL
	 */
	private ClientSqlHelper csql = null;
	private ClientDisSqlHelper cdsql = null;
	
	private boolean asyntaskIsFinished = true;
	private NumberSqlHelper nsql = null;
	
	private Context context;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.client_list_layout);
		context = this;
		gson = new Gson();
		init();
		csql = new ClientSqlHelper();
		csql.open(BizApp.getInstance().getSqlHelper());
		cdsql = new ClientDisSqlHelper();
		cdsql.open(BizApp.getInstance().getSqlHelper());
		nsql = new NumberSqlHelper();
		nsql.open(BizApp.getInstance().getSqlHelper());
	}

	private void init() {
		txtKeyword = (EditText) findViewById(R.id.txt_keyword);
		btnSearch = (Button) findViewById(R.id.btn_search);
		btnRef = (Button) findViewById(R.id.btn_refresh);
		btnMap = (Button) findViewById(R.id.btn_history);
		btnMap.setBackgroundResource(R.drawable.btn_earth_press);
		btnMap.setVisibility(View.VISIBLE);
		btnMap.setOnClickListener(this);
		btnRef.setOnClickListener(this);
		btnSearch.setOnClickListener(this);
		btnRef.setVisibility(View.GONE);
	 
		listView = (ListView) findViewById(R.id.listview);
	}
	private int isPage = 0;
	@Override
	protected void onResume() {
		super.onResume();

		if(BizApp.getInstance().isNetworkAvailable() || BizApp.getInstance().isWiFiActive()){
			if (asyntaskIsFinished) {
				pageIndex = 0;
				showLoading();
				getData();
			}
		}else{
			showLoading();
			registerLoadStatus(TAG);
			getDataFromSQL();
			finishedLoad(TAG);
		}
	}

	public class Phone implements Serializable {

		/**
		 *
		 */
		private static final long serialVersionUID = -6760611499805749529L;
		@SerializedName("phone")
		public String phone;
	}

 

	/**
	 * 从服务端获取数据
	 */
	private void getData() {
		registerLoadStatus(TAG);
		new ServiceAsynTask<ClientListInfo>() {

			@Override
			protected ClientListInfo callService() throws IOException,
					JsonParseException, AssertionError, BizException,Exception {
				if(pageIndex == 0){
					isPage = 0;
				}else{
					isPage ++;
				}
				CommonBody body = new CommonBody();
				if (StringUtil.isEmptyOrNull(keyword)) {
					body.setCommand(1);
				} else {
					body.setCommand(2);
				}
				body.setImsi(BizApp.getInstance().getIMSI());
				body.setVersion(getString(R.string.app_version));
				LocationPageinfo pageInfo = new LocationPageinfo();
 
//				pageInfo.begin = 1;
//				pageInfo.end = pageSize;
				pageInfo.begin = pageIndex * pageSize + isPage;
				pageInfo.end = (pageIndex + 1) * pageSize + isPage;
				pageInfo.lon = BizApp.getInstance().getLon();
				pageInfo.lat = BizApp.getInstance().getLat();
				if (!StringUtil.isEmptyOrNull(keyword)) {
					pageInfo.name = keyword;
				}
				return ServiceHelper.getInstance().postData(
						ServiceHost.getClientsURL(), gson.toJson(body),
						gson.toJson(pageInfo), ClientListInfo.class);
			}

			@Override
			protected void runWithResult(ClientListInfo result)
					throws Exception {

				dealResult(result);
				hideLoading();

				asyntaskIsFinished = true;
				finishedLoad(TAG);
			}

			@Override
			protected void runWithError(ClientListInfo result, int iErrorCode)
					throws Exception {
				if (result == null) {
					asyntaskIsFinished = true;
					loadingFailed(TAG, iErrorCode);
				}
				if(PrefsUtils.getURL().equals(StringUtil.URL1)){
					PrefsUtils.setURL(StringUtil.URL2);
				}else if(PrefsUtils.getURL().equals(StringUtil.URL2)){
					PrefsUtils.setURL(StringUtil.URL1);
				}
				try{
					getDataByUrl2();
				}catch (Exception e) {
				}
				hideLoading();

			}
		}.execute();
	}

	private void getDataByUrl2() {
		registerLoadStatus(TAG);
		new ServiceAsynTask<ClientListInfo>() {

			@Override
			protected ClientListInfo callService() throws IOException,
					JsonParseException, AssertionError, BizException,Exception {
				if(pageIndex == 0){
					isPage = 0;
				}else{
					isPage ++;
				}
				CommonBody body = new CommonBody();
				if (StringUtil.isEmptyOrNull(keyword)) {
					body.setCommand(1);
				} else {
					body.setCommand(2);
				}
				body.setImsi(BizApp.getInstance().getIMSI());
				body.setVersion(getString(R.string.app_version));
				LocationPageinfo pageInfo = new LocationPageinfo();
 
//				pageInfo.begin = 1;
//				pageInfo.end = pageSize;
				pageInfo.begin = pageIndex * pageSize + isPage;
				pageInfo.end = (pageIndex + 1) * pageSize + isPage;
				pageInfo.lon = BizApp.getInstance().getLon();
				pageInfo.lat = BizApp.getInstance().getLat();
				if (!StringUtil.isEmptyOrNull(keyword)) {
					pageInfo.name = keyword;
				}
				return ServiceHelper.getInstance().postData(
						ServiceHost.getClientsURL(), gson.toJson(body),
						gson.toJson(pageInfo), ClientListInfo.class);
			}

			@Override
			protected void runWithResult(ClientListInfo result)
					throws Exception {

				dealResult(result);
				hideLoading();

				asyntaskIsFinished = true;
				finishedLoad(TAG);
			}

			@Override
			protected void runWithError(ClientListInfo result, int iErrorCode)
					throws Exception {
				if (result == null) {
					asyntaskIsFinished = true;
					loadingFailed(TAG, iErrorCode);
				}
				if(PrefsUtils.getURL().equals(StringUtil.URL1)){
					PrefsUtils.setURL(StringUtil.URL2);
				}else if(PrefsUtils.getURL().equals(StringUtil.URL2)){
					PrefsUtils.setURL(StringUtil.URL1);
				}
				getDataFromSQL();
				hideLoading();

			}
		}.execute();
	}
	
	private int numInSQL = 0;
	private int numInService = 0;
	private void dealResult(ClientListInfo result){
		
		numInSQL = csql.getCount();
	 
		if (null != result) {
			datasource = result;
			numInService = datasource.getClients().size();
		}

		if (numInService != numInSQL) {
			csql.delete();
			for (int i = 0; i < datasource.getClients().size(); i++) {
				 
				csql.addClientInfo(datasource.getClients().get(i));
			}
//			Log.e("TAG", "初始保存sql size： = " + csql.getCount());
		}
		bindData();
	}
	
	
	private void getDataFromSQL(){
		numInSQL = csql.getCount();
		Log.e("TQA", "sql size: = " + csql.getCount());
		if(numInSQL > 0){
			datasource = csql.getClientInfo(0, numInSQL, null);
			bindData();
		}else{
			Log.e("TAG", "=============");
			Toast.makeText(context, "获取数据失败", Toast.LENGTH_SHORT).show();
		}
	}
	
	private void bindData() {
		if (adapter == null || pageIndex == 0) {
			adapter = new ClientAdapter(datasource, this);
			adapter.setDelegate(this);
			adapter.setHandler(this);
			listView.setAdapter(adapter);
		} else {
			if (pageIndex >= 1) {
				adapter.appendDataSource(datasource);
				adapter.notifyDataSetChanged();
			}
		}
		totalRow = datasource.getRows();
		if (totalRow > (pageIndex + 1) * pageSize) {
			isNeedLoading = true;
		} else {
			isNeedLoading = false;
		}
		isNeedLoading = false;
	}

	@Override
	public void onLoadingRowShowing(LoadingAdapter adapter) {
		if (pageIndex * pageSize < totalRow) {
			if (asyntaskIsFinished) {
				pageIndex++;
				getData();
				asyntaskIsFinished = false;
			}
		}
	}

	@Override
	public boolean needLoading() {
		return isNeedLoading;
	}

	private void showMap() {
		if (datasource == null) {
			return;
		}
		if(BizApp.getInstance().isWiFiActive() || BizApp.getInstance().isNetworkAvailable()){
//			for(ClientInfo info: datasource.getClients()){
//				Log.e("TAG", "client 经纬度 lat: = " + info.getLat() + " , lon: = " + info.getLon());
//			}
			Bundle bundle = new Bundle();
			bundle.putSerializable(PersistentKeyUtil.CLIENTS_STRING, datasource);
			IntentUtil.redirectToNext(ClientListActivity.this,
					ClientsMapActivity.class, bundle);
		}else{
			Toast.makeText(context, "无可用网络！", Toast.LENGTH_SHORT).show();
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_refresh:
			showLoading();
			getData();
			break;
		case R.id.btn_history:
			showMap();
			break;
		case R.id.btn_search:
			keyword = txtKeyword.getText().toString().trim();
			if (StringUtil.isEmptyOrNull(keyword)) {
				Toast.makeText(this, "请输入查询关键字", Toast.LENGTH_SHORT).show();
			} else {
				showLoading();
				getDataByKey(keyword);
			}
			break;
		default:
			break;
		}
	}

	private void getDataByKey(String keyword){
		numInSQL = csql.getCount();
		if(numInSQL > 0){
			datasource = csql.getClientInfo(0, numInSQL, keyword);
			bindData();
			finishedLoad(TAG);
		}else{
			Toast.makeText(context, "暂无客户！", Toast.LENGTH_LONG).show();
		}
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
			DialogUtil.getExitAppDialog(this).show();
			return false;
		}
		return super.onKeyDown(keyCode, event);
	}
}
